<?php
/**
 * 知食
 * User: Tsang
 * Date: 2017/12/15 11:11
 *
 */

namespace app\api\logic;


use app\api\BaseModel;
use think\Db;

class KnowFoods extends BaseModel
{

    /**
     * 知食列表
     */
    public function index()
    {
        if (array_key_exists('page', $this->requestData)) {
            $page = intval($this->requestData['page']) > 0 ? intval($this->requestData['page']) : 1;
        } else {
            $page = 1;
        }
        if (array_key_exists('limit', $this->requestData)) {
            $limit = intval($this->requestData['limit']) > 0 ? intval($this->requestData['limit']) : 10;
        } else {
            $limit = 10;
        }
        $m_foods_knowleledge = db('foods_knowledge');
        $where = [
            'status' => ARTICLE_STATUS_SUCCESS
        ];
        $count = $m_foods_knowleledge->where($where)->count();
        $list = array();
        if($count > 0){
            $list = $m_foods_knowleledge->where($where)
                ->order('sort desc')
                ->order('create_time desc')
                ->page($page, $limit)
                ->field('title,create_time,thumb_num,create_name,status,image,sort')
                ->select();
            foreach($list as &$l){
                $l['image'] =  __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$l['image']);
                $l['create_time'] = date('Y-m-d',$l['create_time']);
            }
        }
        return array(
            'list' => $list,
            'page' => $page,
            'limit' => $limit,
            'count' => $count,
        );
    }

    /**
     * 知食详情
     */
    public function detail()
    {
        $res = $this->checkData(
            ["id"],
            ["知食ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $detail = db('foods_knowledge')->where(['id' => intval($this->requestData['id']), 'status' => ARTICLE_STATUS_SUCCESS])->find();
        if (empty($detail)) return array('message' => '找不到对应的详情');
        $detail['content'] = 'http://'.$_SERVER['HTTP_HOST'].'/Index/index/goods_knowledge_info?type=foods_knowledge_info&id='.$detail['id'];
        $detail['image'] =  __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$detail['image']);
        if(!empty($this->user)){
            $collection = db('foods_knowledge_collection')->where(['uid' => $this->user['uid'],'fk_id' => $detail['id']])->find();
            if($collection){
                $detail['is_collect'] = 1;
            }else{
                $detail['is_collect'] = 0;
            }
            $thumb = db('foods_knowledge_thumb')->where(['uid' => $this->user['uid'],'fk_id' => $detail['id']])->find();
            if($thumb){
                $detail['is_thumb'] = 1;
            }else{
                $detail['is_thumb'] = 0;
            }
        }
        $detail['create_time'] = date('Y-m-d',$detail['create_time']);
        return $detail;
    }

    /**
     * 评论
     */
    public function commentList(){
        $res = $this->checkData(
            ["id"],
            ["知食ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        //评论列表
        if (array_key_exists('page', $this->requestData)) {
            $page = intval($this->requestData['page']) > 0 ? intval($this->requestData['page']) : 1;
        } else {
            $page = 1;
        }
        if (array_key_exists('limit', $this->requestData)) {
            $limit = intval($this->requestData['limit']) > 0 ? intval($this->requestData['limit']) : 10;
        } else {
            $limit = 10;
        }
        $where = [
            'fk_id' => $this->requestData['id'],
            'delete' => '0',
            'comment_id' => 0
        ];
        $m_fkc = db('foods_knowledge_comment');
        $count = $m_fkc->where($where)->count();
        if($count > 0){
            $data = $m_fkc->where($where)->order('id desc')->page($page,$limit)->select();
            if(!empty($data)){
                $list = $m_fkc->where(['comment_id' => ['in',array_column($data,'id')]])->order('comment_id')->select();
                if(!empty($list)){
                    //整理数据
                    $comment_ids = array_column($list, 'comment_id');
                    $num = array_count_values($comment_ids);
                    //点赞列表
                    $thumb = db('foods_knowledge_comment_thumb')->where(['comment_id' => ['in', array_unique($comment_ids)]])->order('comment_id')->select();
                    $t_comment_ids = array_column($thumb, 'comment_id');
                    $t_num = array_count_values($t_comment_ids);
                    foreach ($data as &$a) {
                        if (array_key_exists($a['id'], $num)) {
                            $key = array_search($a['id'], $comment_ids);
                            if ($num[$a['id']] > 2) {
                                $a['children'] = array_slice($list, $key, 2);
                            } else {
                                $a['children'] = array_slice($list, $key, $num[$a['id']]);
                            }
                            $a['children_num'] = $num[$a['id']];
                        }
                        if (!empty($this->user) && array_key_exists($a['id'], $t_num)) {
                            $key = array_search($a['id'], $t_comment_ids);
                            $res = array_slice($thumb, $key, $t_num[$a['id']]);
                            $a['is_thumb'] = array_search($this->user['uid'], array_column($res, 'uid')) !== false ? 1 : 0;
                        } else {
                            $a['is_thumb'] = 0;
                        }

                        $a['create_time'] = date('Y-m-d',$a['create_time']);
                    }
                }
            }
        }else{
            $data = array();
        }
        return array(
            'list' => $data,
            'page' => $page,
            'limit' => $limit,
            'count' => $count,
        );
    }

    /**
     * 评论详情
     */
    public function commentDetail(){
        $res = $this->checkData(
            ["id"],
            ["评论ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $id = intval($this->requestData['id']);
        $comment = db('foods_knowledge_comment')->where('(id ='.$id.' or comment_id = '.$id.') and `delete` = "0"')->order('id')->select();
        if(empty($comment) || $comment[0]['id'] != $id) return array('message' => '找不到评论');
        $data = $comment[0];
        if(count($comment) > 1){
            unset($comment[0]);
            $data['children'] = array_merge($comment);
        }else{
            $data['children'] = [];
        }
        $data['children_num'] = count($data['children']);
        if(!empty($this->user)){
            $thumb = db('foods_knowledge_comment_thumb')->where(['comment_id' => $id,'uid' => $this->user['uid']])->find();
            $data['is_thumb'] = (!$thumb) ? 0 : 1;
        }else{
            $data['is_thumb'] = 0;
        }
        $data['create_time'] = date('Y-m-d h:i:s',$data['create_time']);
        return $data;


    }


    /**
     * 收藏
     */
    public function collection()
    {
        $res = $this->checkData(
            ["id", "type"],
            ["知食ID不能为空", "操作类型不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $type = intval($this->requestData['type']);
        if (!in_array($type, [1, 2])) return array('message' => '操作类型错误');
        $detail = db('foods_knowledge')->where(['id' => intval($this->requestData['id']), 'status' => ARTICLE_STATUS_SUCCESS])->find();
        if (empty($detail)) return array('message' => '找不到对应的详情');
        $m_fkc = db('foods_knowledge_collection');
        $collection = $m_fkc->where(['fk_id' => $detail['id'], 'uid' => $this->user['uid']])->find();
        switch ($type) {
            case 1://收藏
                if ($collection) return array('message' => '您已经收藏过了');
                $data = array(
                    'uid' => $this->user['uid'],
                    'create_time' => TIMESTAMP,
                    'fk_id' => $detail['id'],
                );
                if (!$m_fkc->insert($data)) return array('message' => '操作失败');
                break;
            case 2://取消收藏
                if (!$collection) return array('message' => '您未收藏过');
                if (!$m_fkc->where(['id' => $collection['id']])->delete()) return array('message' => '操作失败');
                break;
        }
        return array();
    }


    /**
     * 点赞
     */
    public function thumb()
    {
        $res = $this->checkData(
            ["id"],
            ["知食ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $m_fk = db('foods_knowledge');
        $detail = $m_fk->where(['id' => intval($this->requestData['id']), 'status' => ARTICLE_STATUS_SUCCESS])->find();
        if (empty($detail)) return array('message' => '找不到知食');
        $m_fkt = db('foods_knowledge_thumb');
        $thumb = $m_fkt->where(['fk_id' => $detail['id'], 'uid' => $this->user['uid']])->find();
        if ($thumb) return array('message' => '您已经点赞过了');
        $data = array(
            'uid' => $this->user['uid'],
            'create_time' => TIMESTAMP,
            'fk_id' => $detail['id'],
        );
        Db::startTrans();
        try{
            $m_fkt->insert($data);
            $m_fk->where(['id' => intval($this->requestData['id'])])->setInc('thumb_num');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return array('message' => '操作失败');
        }
        return array();
    }


    /**
     * 评论
     */
    public function comment()
    {
        $res = $this->checkData(
            ["id","content"],
            ["知食详情ID不能为空","评论内容不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $m_fk = db('foods_knowledge');
        $detail = $m_fk->where(['id' => intval($this->requestData['id']), 'status' => ARTICLE_STATUS_SUCCESS])->find();
        if (empty($detail)) return array('message' => '找不到对应的详情');
        $this->user['headimage'] = get_headimage($this->user['headimage'],$this->user['userId']);
        $data = array(
            'fk_id' => $detail['id'],
            'memid' => $this->user['uid'],
            'mem_avatar' => $this->user['headimage'],
            'mem_name' => $this->user['nickname'],
            'create_time' => TIMESTAMP,
            'content' => htmlspecialchars($this->requestData['content'])
        );
        $m_fkc = db('foods_knowledge_comment');
        if(array_key_exists('comment_id',$this->requestData)){
            $comment = $m_fkc->where(['id' => intval($this->requestData['comment_id']),'delete' => 0])->find();
            if(!$comment) return array('message' => '找不到评论');
            $data['comment_id'] = intval($this->requestData['comment_id']);
        }
        if(!$m_fkc->insert($data)) return array('message' => '操作失败');
        return array();

    }

    /**
     * 评论点赞
     */
    public function commentThumb(){
        $res = $this->checkData(
            ["comment_id"],
            ["评论ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $m_fkc = db('foods_knowledge_comment');
        $comment = $m_fkc->where(['id' => intval($this->requestData['comment_id']),'delete' => 0])->find();
        if(!$comment) return array('message' => '找不到评论');
        $m_fkct = db('foods_knowledge_comment_thumb');
        $is_thumb = $m_fkct->where(['comment_id' => $comment['id'],'uid' => $this->user['uid']])->find();
        if($is_thumb) return array('message' => '您已经点赞此评论');
        Db::startTrans();
        try{

            $m_fkc->where(['id' => intval($this->requestData['comment_id']),'delete' => 0])->setInc('thumb_num');

            $m_fkct->insert([
                'uid' => $this->user['uid'],
                'create_time' => TIMESTAMP,
                'comment_id' => $comment['id'],
            ]);

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return array('message' => '操作失败');
        }
        return array();
    }

    /**
     * 评论盖楼
     */
    private function build($data, $comment_ids = array(), $result = array())
    {
        if (empty($data)) return $result;
        if (empty($result)) {
            $comment_ids = array_column($data, 'comment_id');
            $count = count($comment_ids);
            for ($i = 0; $i < $count; $i++) {
                $key = array_search(0, $comment_ids);
                if ($key === false) {
                    break;
                } else {
                    $result[] = $data[$key];
                    unset($comment_ids[$key]);
                }
            }
            $result = $this->build($data, $comment_ids, $result);
        } else {
            foreach ($result as &$value) {
                $count = count($comment_ids);
                if ($count > 0) {
                    for ($i = 0; $i < $count; $i++) {
                        $key = array_search($value['id'], $comment_ids);
                        if ($key === false) {
                            break;
                        } else {
                            $value['children'] = $data[$key];
                            unset($comment_ids[$key]);
                        }
                    }
                    if (array_key_exists('children', $value)) {
                        $value = $this->build($data, $comment_ids, $value['children']);
                    }
                } else {
                    break;
                }
            }
        }
        return $result;
    }


    /**
     * 收藏列表
     */
    public function myCollect(){
        $list = db('foods_knowledge_collection')->alias('fkc')
            ->join('foods_knowledge fk','fk.id = fkc.fk_id')
            ->where(['fkc.uid' => $this->user['uid']])
            ->order('fkc.fk_id desc')
            ->select();
        foreach($list as &$l){
            $l['image'] =  __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$l['image']);
            $l['content'] = htmlspecialchars_decode($l['content']);
            $l['create_time'] = date('Y-m-d h:i:s',$l['create_time']);
        }
        return $list;
    }


    /**
     * 轮播图
     */
    public function banner(){
        $data = db('banner')->where(['type' => 1,'status' => 1])->select();
        foreach($data as &$d){
            $d['pic'] = __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$d['pic']);
        }
        return $data;
    }
}